package com.romin.service;

import com.google.common.collect.Lists;
import com.romin.dao.ManagerDao;
import com.romin.pojo.Manager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author cloud.eve
 */
@Component
public class CommonUserDetailsService implements UserDetailsService {
    private static Logger logger = LoggerFactory.getLogger(CommonUserDetailsService.class);

    @Resource
    private ManagerDao managerDao;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Manager manager = managerDao.findByUserName(s);
        User user = null;
        try {
            user = new User(manager.getUserName(), manager.getPassword(), true, true, true, true, getAuthorities(manager.getAccessType()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new UsernameNotFoundException(e.getMessage());
        }
        return user;
    }

    public List<Manager> loadUserByPage(){
        List<Manager> managers = Lists.newArrayList(managerDao.findAll());
        return managers;
    }


    /**
     * 获得访问角色权限
     *
     * @param access
     * @return
     */
    public Collection<GrantedAuthority> getAuthorities(Integer access) {

        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);

        // 所有的用户默认拥有ROLE_USER权限
        logger.debug("Grant ROLE_USER to this user");
        authList.add(new SimpleGrantedAuthority("ROLE_USER"));

        // 如果参数access为1.则拥有ROLE_ADMIN权限
        if (access < 3) {
            logger.debug("Grant ROLE_ADMIN to this user");
            authList.add(new SimpleGrantedAuthority("ROLE_MANAGER"));
        }
        if (access < 2) {
            logger.debug("Grant ROLE_ADMIN to this user");
            authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        }

        return authList;
    }
}
